import {createRouter, createWebHistory} from 'vue-router'
import LoginView from '../views/login/index.vue'
import {getUser} from "@/api/user.js";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/forgetPassword',
      name: 'forgetPassword',
      component: () => import('../views/forgetPassword/index.vue')
    },
    {
      path: '/distributor',
      name: 'distributor',
      component: () => import('../views/distributor/layout/index.vue'),
      children: [
        {
          path: 'home',
          name: 'distributorHome',
          component: () => import('../views/distributor/home/index.vue'),
          meta: {
            role: 'distributor',
            title: '首页'
          }
        },
        {
          path: 'subManage',
          name: 'distributorManage',
          component: () => import('../views/distributor/subManage/index.vue'),
          meta: {
            role: 'distributor',
            title: '经销商管理'
          }
        },
        {
          path: 'suppliers',
          name: 'suppliersManage',
          component: () => import('../views/distributor/suppliers/index.vue'),
          meta: {
            role: 'distributor',
            title: '供应商管理'
          }
        },
        {
          path: 'order',
          name: 'orderManage',
          component: () => import('../views/distributor/order/index.vue'),
          meta: {
            role: 'distributor',
            title: '订单管理'
          }
        },
        {
          path: 'demo',
          name: 'demoPassword',
          component: () => import('../views/demo/password/index.vue'),
          meta: {
            title: '密码强度'
          }
        },
      ]
    },
    {
      path: '/401',
      name: 'unauthorized',
      component: () => import('@/views/error/401.vue')
    },
    {
      path: '/404',
      name: 'notFound',
      component: () => import('@/views/error/404.vue')
    },
    {
      path: '/:xxxx(.*)*',
      name: 'ErrorPage',
      redirect: '/404'
    },
  ]
})

router.beforeEach(async (to, from, next) => {
  // const publicPaths = ['/login', '/forgetPassword', '/404', '/401']  // 公开路径
  // const authRequired = !publicPaths.includes(to.path)
  //
  // console.log(to.meta.role)
  //
  // if (authRequired) {
  //   try {
  //     const {data: user} = await getUser()
  //     console.log(user.user_type)
  //     const hasAccess = to.meta.role === undefined || to.meta.role === user.user_type
  //     if (hasAccess) {
  //       next()
  //     }else {
  //       // 应该重定向至401，提示用户没有权限
  //       next('/401')
  //     }
  //   }catch (e) {
  //     console.log("Error",e)
  //      next('/')
  //   }
  // }else {
    next()
  // }
})

export default router
